/*
 * Copyright 2012 Gregor Schauer
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package at.schauer.gregor.vienna.serializer.builder;

import at.schauer.gregor.vienna.context.ViennaContext;
import at.schauer.gregor.vienna.serializer.builder.discover.NamedParameterDiscoverer;
import at.schauer.gregor.vienna.serializer.builder.discover.ParameterDiscoverer;
import at.schauer.gregor.vienna.util.ViennaUtils;
import org.springframework.beans.BeanUtils;

import javax.inject.Inject;
import java.lang.reflect.Constructor;
import java.util.Map;

/**
 * @author Gregor Schauer
 */
public class JSR330ConstructorBuilder<T> extends ParameterDiscovererBuilder<T> {
	public JSR330ConstructorBuilder(ViennaContext ctx) {
		super(ctx);
	}

	@Override
	@SuppressWarnings("unchecked")
	public <E extends T> E construct(Map<String, Object> map, Class<E> clazz) {
		for (Constructor<E> ctor : (Constructor<E>[]) clazz.getDeclaredConstructors()) {
			if (ctor.isAnnotationPresent(Inject.class)) {
				Class<?>[] parameterTypes = ctor.getParameterTypes();
				Object[] args = new Object[parameterTypes.length];

				ParameterDiscoverer discoverer = discovererMap.get(clazz);
				if (discoverer == null) {
					discoverer = new NamedParameterDiscoverer(parameterTypes);
					discovererMap.put(clazz, discoverer);
				}
				String[] parameterNames = discoverer.getParameterNameDiscoverer().getParameterNames(ctor);

				for (int i = 0; i < parameterTypes.length; i++) {
					args[i] = map.get(parameterNames[i]);
					if (args[i] instanceof String) {
						args[i] = ViennaUtils.DeserializationUtils.load(ctx, parameterTypes[i], (String) args[i]);
					}
				}
				return BeanUtils.instantiateClass(ctor, args);
			}
		}
		return null;
	}
}
